<script setup lang="ts">
import { darkTheme, NIcon } from 'naive-ui';
import NetworkOutline from '@vicons/ionicons5/Globe';
import PlayOutline from '@vicons/ionicons5/Play';
import PauseOutline from '@vicons/ionicons5/Pause';
import SunnyOutline from '@vicons/ionicons5/Sunny';
import MoonOutline from '@vicons/ionicons5/Moon';
import ListOutline from '@vicons/ionicons5/List';
import SettingsOutline from '@vicons/ionicons5/Settings';
import { useTransactionsStore } from './stores/transactions';
import { apiClient } from './api/client';

// 路由
const router = useRouter();
const route = useRoute();

// Store
const transactionsStore = useTransactionsStore();

// 状态
const theme = ref<typeof darkTheme | null>(null);
const activeKey = ref('transactions');
const proxyStatus = ref(true);
const proxyLoading = ref(false);

// 菜单选项
const menuOptions = [
  {
    label: '请求记录',
    key: 'transactions',
    icon: () => h(NIcon, { component: ListOutline })
  },
  {
    label: '规则配置',
    key: 'rules',
    icon: () => h(NIcon, { component: SettingsOutline })
  }
];

// 计算属性
const totalRequests = computed(() => {
  return transactionsStore.transactions.length;
});

// 方法
function handleMenuSelect(key: string) {
  activeKey.value = key;
  router.push(`/${key}`);
}

function toggleTheme() {
  theme.value = theme.value === null ? darkTheme : null;
}

async function toggleProxy() {
  try {
    proxyLoading.value = true;
    
    // 调用切换API，后端会自动判断当前状态并切换
    const response = await apiClient.toggleProxy();
    
    // 根据返回的状态更新前端状态
    if (response.success) {
      proxyStatus.value = response.status === 'started';
    }
  } catch (error) {
    console.error('切换代理状态失败:', error);
    // 发生错误时重新检查状态
    await checkProxyStatus();
  } finally {
    proxyLoading.value = false;
  }
}

async function checkProxyStatus() {
  try {
    const response = await apiClient.getProxyStatus();
    // 检查综合状态：代理服务器运行 && 系统代理已设置
    proxyStatus.value = response.enabled || (response.running && response.systemProxy?.isSet);
    console.log('代理状态检查:', {
      running: response.running,
      systemProxySet: response.systemProxy?.isSet,
      enabled: response.enabled,
      final: proxyStatus.value
    });
  } catch (error) {
    console.error('获取代理状态失败:', error);
    proxyStatus.value = false; // 错误时默认为停用
  }
}

// 清空所有记录
async function clearAllRecords() {
  try {
    const result = await transactionsStore.clearTransactions();
    
    if (result.serverCleared && result.localCleared) {
      console.log('✅ 已清空所有记录（包括服务端和本地）');
    } else if (result.localCleared && !result.serverCleared) {
      console.log('⚠️ 已清空本地记录，但服务端清空失败（可能服务器未连接）');
    } else {
      console.log('❌ 清空记录时发生问题');
    }
  } catch (error) {
    console.error('❌ 清空记录失败:', error);
  }
}

// 移除旧的WebSocket初始化逻辑，改用store管理

// 生命周期
onMounted(async () => {
  // 根据当前路由设置活动菜单
  if (route.path.includes('rules')) {
    activeKey.value = 'rules';
  } else {
    activeKey.value = 'transactions';
  }

  // 初始化 IndexedDB 并加载历史数据
  await transactionsStore.initDatabase();
  await transactionsStore.loadFromIndexedDB();

  // 检查代理状态
  checkProxyStatus();

  // 初始化WebSocket（通过store管理）
  transactionsStore.initWebSocketListeners();
});

onUnmounted(() => {
  // 清理WebSocket连接（通过store管理）
  transactionsStore.cleanupWebSocketListeners();
});
</script>

<template>
  <n-config-provider :theme="theme">
    <n-message-provider>
      <n-dialog-provider>
        <n-notification-provider>
          <div class="app" :data-theme="theme ? 'dark' : 'light'">
            <!-- 头部导航 -->
            <header class="app-header">
              <div class="header-content">
                <div class="logo">
                  <n-icon :component="NetworkOutline" size="24" />
                  <span>Node Fiddler</span>
                </div>
                
                <n-menu
                  v-model:value="activeKey"
                  mode="horizontal"
                  :options="menuOptions"
                  @update:value="handleMenuSelect"
                />
                
                <div class="header-actions">
                  <n-space>
                    <n-button
                      :type="proxyStatus ? 'success' : 'default'"
                      @click="toggleProxy"
                      :loading="proxyLoading"
                    >
                      <template #icon>
                        <n-icon :component="proxyStatus ? PlayOutline : PauseOutline" />
                      </template>
                      {{ proxyStatus ? '代理已启用' : '代理已停用' }}
                    </n-button>
                    
                    <n-popconfirm
                      @positive-click="clearAllRecords"
                      positive-text="确定"
                      negative-text="取消"
                    >
                      <template #trigger>
                        <n-button type="error" ghost>
                          清空记录
                        </n-button>
                      </template>
                      确定要清空所有历史记录吗？此操作不可恢复。
                    </n-popconfirm>
                    
                    <n-button circle @click="toggleTheme">
                      <template #icon>
                        <n-icon :component="theme === null ? MoonOutline : SunnyOutline" />
                      </template>
                    </n-button>
                  </n-space>
                </div>
              </div>
            </header>

            <!-- 主内容区域 -->
            <main class="app-main">
              <router-view />
            </main>

            <!-- 状态栏 -->
            <footer class="app-footer">
              <n-space justify="space-between">
                <div class="status-info">
                  <n-space>
                    <n-tag 
                      :type="transactionsStore.wsConnected ? 'success' : 
                            transactionsStore.wsReconnecting ? 'warning' : 'error'" 
                      size="small"
                    >
                      <span v-if="transactionsStore.wsConnected">WebSocket已连接</span>
                      <span v-else-if="transactionsStore.wsReconnecting">
                        重连中 ({{ transactionsStore.wsReconnectAttempts }})
                      </span>
                      <span v-else>WebSocket断开</span>
                    </n-tag>
                    
                    <n-button 
                      v-if="!transactionsStore.wsConnected && !transactionsStore.wsReconnecting"
                      size="tiny" 
                      type="primary" 
                      @click="transactionsStore.forceReconnectWebSocket"
                    >
                      重连
                    </n-button>
                    
                    <n-tag size="small">
                      总请求数: {{ totalRequests }}
                    </n-tag>
                    
                    <n-tag v-if="transactionsStore.filteredCount > 0" type="info" size="small">
                      共 {{ transactionsStore.filteredCount }} 条记录
                    </n-tag>
                  </n-space>
                </div>
                
                <div class="app-info">
                  <span>Node Fiddler v1.0.0</span>
                </div>
              </n-space>
            </footer>
          </div>
        </n-notification-provider>
      </n-dialog-provider>
    </n-message-provider>
  </n-config-provider>
</template>

<style scoped lang="less">
.app {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--bg-secondary);
  
  .app-header {
    background: var(--bg-color);
    border-bottom: 1px solid var(--border-color);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    z-index: 1000;
    
          .header-content {
        display: flex;
        align-items: center;
        padding: 0 24px;
        height: 64px;
      
      .logo {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-right: 40px;
        font-size: 18px;
        font-weight: 600;
        color: #1890ff;
        
        :deep(.n-icon) {
          color: #1890ff;
        }
      }
      
      .header-actions {
        margin-left: auto;
      }
    }
  }
  
  .app-main {
    flex: 1;
    overflow: hidden;
    background: var(--bg-secondary);
  }
  
  .app-footer {
    background: var(--bg-color);
    border-top: 1px solid var(--border-color);
    padding: 12px 24px;
    font-size: 12px;
    color: var(--text-color);
    
    .status-info {
      display: flex;
      align-items: center;
    }
    
    .app-info {
      display: flex;
      align-items: center;
    }
  }
}

:deep(.n-menu--horizontal) {
  flex: 1;
  background: transparent;
  
  .n-menu-item {
    height: 64px;
    margin: 0 4px;
    border-radius: 6px;
  }
  
  .n-menu-item--selected {
    background: #e6f7ff;
    color: #1890ff;
  }
}

:deep(.n-button) {
  font-weight: 500;
}

:deep(.n-tag) {
  font-weight: 500;
}


</style>
